<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>绑定 Passkey（登录用户）</title>
</head>
<body>
  <h2>绑定 Passkey 到当前用户</h2>

  <button onclick="register()">注册绑定</button>
  <pre id="log"></pre>

  <script>
    const log = msg => {
      document.getElementById('log').textContent += `${msg}\n`;
    };

    function base64urlToBase64(base64url) {
      base64url = base64url
        .replace(/-/g, '+')
        .replace(/_/g, '/');
      // 补齐 =
      while (base64url.length % 4) {
        base64url += '=';
      }
      return base64url;
    }

    const decode = b64url => {
          const base64 = base64urlToBase64(b64url);
          return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
        };
    const encode = buf => {
      const base64 = btoa(String.fromCharCode(...new Uint8Array(buf)));
      return base64ToBase64Url(base64);
    };
    function base64ToBase64Url(base64) {
      return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    const getToken = () => {
      return '1'; // 你可以改成从 cookie、sessionStorage 取
    };

    async function register() {
      const token = getToken();
      if (!token) {
        log('❌ 未找到 token，请登录后再试。');
        return;
      }

      log('请求注册选项...');
        const url = `/passkey/register/options?id=`+token;
      const res = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!res.ok) {
        log('❌ 获取注册选项失败');
        return;
      }
      console.log(res,"11111");
      const options = await res.json();
      const option = options.data;

      option.challenge = decode(option.challenge);
      option.user.id = decode(option.user.id);
      delete option.extensions;

      console.log(option,"ssss");
      const cred = await navigator.credentials.create({ publicKey: {
          challenge: option.challenge,  // 这里是已经解码的 challenge
          rp: option.rp,  // 注册方信息（无需改变）
          user: option.user,  // 用户信息（已经解码的 user.id）
          pubKeyCredParams: option.pubKeyCredParams,  // 公钥算法参数
          timeout: option.timeout,  // 超时时间
          excludeCredentials: option.excludeCredentials,  // 已注册的凭证列表（如果有）
          authenticatorSelection: option.authenticatorSelection,  // 验证器选择策略
          extensions: option.extensions  // 扩展
    }});

      const response = {
        id: cred.id,
        userId: token,
        rawId: encode(cred.rawId),
        type: cred.type,
        response: {
          clientDataJSON: encode(cred.response.clientDataJSON),
          attestationObject: encode(cred.response.attestationObject),
            // 确保clientExtensionResults非空
          clientExtensionResults: cred.response.clientExtensionResults || {}
        }
      };

     const request =  JSON.stringify(response)
      console.log(request,"ssss");
      log('发送注册响应...');
      const verifyRes = await fetch('/passkey/register/complete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Atayun-Token': token
        },
        body: JSON.stringify(response)
      });

      const result = await verifyRes.json();
      log('注册绑定结果: ' + JSON.stringify(result));
    }
  </script>
</body>
</html>
